from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from app.config.settings import settings


def _normalize_database_url(url: str) -> str:
    """移除误用的插件/认证相关查询参数，避免SQLAlchemy或数据库解析错误。"""
    forbidden_params = {"plugin", "auth_plugin", "default_authentication_plugin"}
    if not any(f"{param}=" in url for param in forbidden_params):
        return url

    split = urlsplit(url)
    query_pairs = parse_qsl(split.query, keep_blank_values=True)
    filtered_pairs = [
        (k, v) for k, v in query_pairs if k.lower() not in forbidden_params
    ]
    normalized_query = urlencode(filtered_pairs, doseq=True)
    return urlunsplit(
        (split.scheme, split.netloc, split.path, normalized_query, split.fragment)
    )


SQLALCHEMY_DATABASE_URL = _normalize_database_url(settings.DATABASE_URL)

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_pre_ping=True,  # 启用连接前检查
    pool_recycle=3600,  # 连接回收时间
    echo=False,  # 禁用SQL日志
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
